package com.itlin.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itlin.constant.MessageConstant;
import com.itlin.entity.PageResult;
import com.itlin.entity.QueryPageBean;
import com.itlin.entity.Result;
import com.itlin.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    //获取当前登录用户的用户名
    @RequestMapping("/getUsername")
    public Result getUsername()throws Exception{
        try{
            org.springframework.security.core.userdetails.User user =
                    (org.springframework.security.core.userdetails.User)
                            SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,user.getUsername());
        }catch (Exception e){
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }

    // 查询用户数据的分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return userService.pageQuery(queryPageBean);
    }

    // 根据用户id 查询关联的角色
    @RequestMapping("/findRolesByUserId")
    public Result findRolesByUserId(Integer userId){
        try{
            List<Integer> roleIds = userService.findRolesByUserId(userId);
            return new Result(true, MessageConstant.GET_ROLE_SUCCESS, roleIds);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_ROLE_FAIL);
        }
    }


    // 更新用户所对应的角色
    @RequestMapping("/updateRoleAndUserId")
    public Result updateRoleAndUserId(Integer userId,@RequestBody Integer[] roleIds){
        try{
            userService.updateRoleAndUserId(userId, roleIds);

            return new Result(true, MessageConstant.SET_ROLE_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.SET_ROLE_FAIL);
        }
    }

    // 添加一个新用户
    @RequestMapping("/add")
    public Result add(@RequestBody com.itlin.pojo.User user){
        try{
            userService.add(user);

            return new Result(true, MessageConstant.ADD_USER_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_USER_FAIL);
        }
    }
}
